﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace sx_windows.utils
{
    class Des
    {
        public static byte[] AES_KEY = {
            0x46, 0x22, 0x5c, 0x5b, 0x7b, 0x52, 0x19,
            0x1b, 0x22, 0x5c, 0x50, 0x5f, 0xd, 0x29,
            0x3f, 0x36, 0x16, 0x2f, 0x3a, 0x0, 0x27,
            0x2d, 0x49, 0x22, 0x10, 0x3c, 0x39, 0x12,
            0x1b, 0x42, 0x47, 0x9, 0x22, 0x32, 0x57,
            0x3a, 0x3, 0x10, 0x46, 0x0, 0x7c, 0x2e,
            0x2b, 0x74, 0x63, 0x22, 0x14, 0x12, 0xf,
            0x65, 0x74, 0x9, 0x7e, 0x46, 0x71, 0x22,
            0x7d, 0x3c, 0x1c, 0x12, 0x0, 0x55, 0x12,
            0x6a, 0x6a, 0x15, 0x75, 0x5d, 0x2f, 0x2d,
            0x72, 0x5a, 0xc, 0x1d, 0x67, 0x12, 0x14,
            0x64, 0x18, 0x63, 0x5f, 0x37, 0x27, 0x22,
            0x7a, 0x27, 0x1e, 0x3c, 0x5, 0xd, 0x61,
            0x30, 0x4, 0x13, 0x55, 0x5a, 0x10, 0x16,
            0x3a, 0x30, 0x70, 0x3d, 0xf, 0x76, 0x6a,
            0x69, 0x46, 0x33, 0x8, 0x72, 0x2d, 0x1b,
            0x5c, 0x61, 0x29, 0x5d, 0x22, 0x2a, 0x45,
            0x50, 0x35, 0x38, 0x2d, 0x2e, 0x58, 0x74,
            0x2c, 0x19, 0x45, 0x4d, 0x50, 0x75, 0x36
        };
        public static string Decrypt(string encryptedString,long timestamp)
        {
            byte[] btKey = getSecKey(timestamp);
            byte[] btIV = getIvKey(timestamp);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Convert.FromBase64String(encryptedString);
                try
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);
                        cs.FlushFinalBlock();
                    }

                    return Encoding.UTF8.GetString(ms.ToArray());
                }
                catch
                {
                    return null;
                }
            }
        }
        private static byte[] getIvKey(long timestamp)
        {
            byte[] bytes = new byte[8];
            int tmp = (int)((timestamp / 1000 % 100) * (timestamp % 100)) % 100;
            for (int i = 0; i < 8; i++)
            {
                bytes[i] = AES_KEY[tmp];
                tmp = bytes[i];
            }
            return bytes;
        }
        private static byte[] getSecKey(long timestamp)
        {
            return getIvKey(timestamp * 2);
        }

    }
}
